import apis from '@/services/apis.ts'
import { NAvatar } from 'naive-ui'
import { useUserStore } from '@/stores/user.ts'
import { useTencentUserStore } from '@/stores/tencentUserStore.ts'

export const useMiaoxinCompanyStore = defineStore(
  'MiaoxinCompanyStore',
  () => {
    const companyWorker = new Worker(new URL('../workers/company.worker.ts', import.meta.url), {
      type: 'module'
    })
    const userStore = useUserStore()
    const tencentUserStore = useTencentUserStore()

    const companies = ref<any[]>([])
    const organizationUsers = reactive<Record<string, any[]>>({})
    const allOrganizationUsers = ref<any[]>([])
    const allOrganizationUsersMap = reactive<Record<string, Record<string, any>>>({})

    const currentCompanyWithUsers = computed(() => {
      return JSON.parse(localStorage.getItem('currentCompanyWithUsers') || '{}')
    })

    const companyList = computed(() => {
      const coms: any[] =
        companies.value.length > 0 ? companies.value : JSON.parse(localStorage.getItem('companyList') || '[]')

      return coms.map((item: any) => {
        item.children = organizationUsers[item.CompanyId] || []
        return item
      })
    })

    const getCompanyList = () => {
      if (localStorage.getItem('companyList')) return

      apis.getCompanyList().then((res) => {
        companies.value = res.map((item: any) => {
          return {
            key: item.CompanyId,
            label: item.CompanyNickName,
            children: [],
            level: 'company',
            ...item
          }
        })

        localStorage.setItem('companyList', JSON.stringify(companies.value))
      })
    }

    const getUserByOrganization = (companyId: string) => {
      if (organizationUsers[companyId]) return

      const userIDs: string[] = []
      const params = new FormData()
      params.append('companyId', companyId)
      apis.getUserByOrganization(params).then((res) => {
        const o: Record<string, any> = {}
        res.map((i: any) => {
          userIDs.push(i.UserId)
          i.key = i.UserId
          i.label = i.UserName
          i.level = 'user'
          i.prefix = () => h(NAvatar, { size: 18, src: i.Avatar || '/logo.png', class: i.IsLogin ? 'grayscale-0' : 'grayscale' })

          if (o[i.DepartmentId]) {
            o[i.DepartmentId].children?.push(i)
          } else {
            o[i.DepartmentId] = {
              key: `${i.CompanyId}-${i.DepartmentId}`,
              label: i.DepartmentName,
              children: [i],
              level: 'department'
            }
          }
        })

        organizationUsers[companyId] = Object.values(o)
      })

      tencentUserStore.getUserProfile({ userIDList: userIDs })
    }

    const getAllOrganizationUsers = (params: { companyId?: string; departmentId?: string; orderBy?: string }) => {
      if (allOrganizationUsers.value.length > 0) {
        return
      }

      apis.getUserByOrganization(params).then((res: any[]) => {
        allOrganizationUsers.value = res
      })
    }

    watch(
      () => allOrganizationUsers,
      (newVal) => {
        const val = toRaw(newVal.value)
        if (val.length === 0 || Object.keys(allOrganizationUsersMap).length > 0) {
          return
        }

        // 处理 worker 返回的数据
        companyWorker.onmessage = (e) => {
          // console.log('company worker return', e, e.data.organizations)
          // 处理后返回的数据
          for (const index in e.data.organizations) {
            allOrganizationUsersMap[index] = e.data.organizations[index]

            // if (allOrganizationUsersMap[index] === undefined) {
            //   allOrganizationUsersMap[index] = e.data.organizations[index]
            // }
          }

          localStorage.setItem(
            'currentCompanyWithUsers',
            JSON.stringify(e.data.organizations[userStore?.userInfo?.CompanyId as string])
          )
          // 结束进程
          companyWorker.terminate()
        }

        // 提交数据给后台进程处理
        companyWorker.postMessage({ organization: val })
      },
      {
        immediate: true,
        deep: true
      }
    )

    const getUserPage = async (userName: string) => {
      if (!userName) return

      const params = new FormData()
      params.append('pageIndex', '1')
      params.append('pageSize', '30')
      params.append('userName', userName)
      let cl: any[] = []
      const o: Record<string, any> = {}
      await apis.getUserPage(params).then((res) => {
        const c: Record<string, any> = {}
        res.DataList.map((i: any) => {
          i.key = i.UserId
          i.label = i.UserName
          i.level = 'user'
          i.prefix = () => h(NAvatar, { size: 18, src: i.Avatar, class: i.IsLogin ? 'grayscale-0' : 'grayscale' })

          if (!c[i.CompanyId]) {
            c[i.CompanyId] = {
              key: i.CompanyId,
              label: i.CompanyNickName,
              children: [],
              level: 'company',
              companyId: i.CompanyId,
              departmentId: i.departmentId
            }
          }

          if (o[i.CompanyId]) {
            if (o[i.CompanyId][i.DepartmentId]) {
              o[i.CompanyId][i.DepartmentId].children?.push(i)
            } else {
              o[i.CompanyId][i.DepartmentId] = {
                key: `${i.CompanyId}-${i.DepartmentId}`,
                label: i.DepartmentName,
                children: [i],
                level: 'department'
              }
            }
          } else {
            o[i.CompanyId] = {
              [i.DepartmentId]: {
                key: `${i.CompanyId}-${i.DepartmentId}`,
                label: i.DepartmentName,
                children: [i],
                level: 'department'
              }
            }
          }

          return i
        })

        cl = Object.values(c)
      })

      return cl.map((item: any) => {
        item.children = Object.values(o[item.companyId])
        return item
      })
    }

    const filterOrganizationUsers = async (userName: string) => {
      if (!userName) return

      allOrganizationUsers.value.filter((item) => {
        // TODO
        console.log(item)
      })
    }

    const getOrganizationUserProfileById = (userId: string) => {
      return allOrganizationUsers.value.find((u) => u.UserId === userId)
    }

    const getOrganizationUserProfileByCompanyId = (companyId: string) => {
      return allOrganizationUsers.value.find((u) => u.CompanyId === companyId)
    }

    /**
     * 获取当前用户所在公司结构
     */
    const getCurrentCompanyWithUsers = () => {
      if (localStorage.getItem('currentCompanyWithUsers')) return

      const params = new FormData()
      params.append('companyId', userStore.userInfo.CompanyId as string)
      apis.getUserByOrganization(params).then((res) => {
        const users: Record<string, any> = {}
        res.map((user: any) => {
          users[user.UserId] = user
        })

        localStorage.setItem('currentCompanyWithUsers', JSON.stringify(users))
      })
    }

    return {
      companyList,
      getCompanyList,
      getUserByOrganization,
      organizationUsers,
      currentCompanyWithUsers,
      getOrganizationUserProfileById,
      getUserPage,
      getAllOrganizationUsers,
      allOrganizationUsers,
      allOrganizationUsersMap,
      filterOrganizationUsers,
      getOrganizationUserProfileByCompanyId,
      getCurrentCompanyWithUsers,
    }
  },
  {
    share: {
      enable: true,
      initialize: true
    }
  }
)
